package com.smart.community.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.entity.property.UserPropertyCompany;
import com.smart.community.commons.result.Result;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.property.mapper.UserPropertyCompanyMapper;
import com.smart.community.property.service.IUserPropertyCompanyService;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.validation.constraints.NotNull;

/**
 * 用户物业公司关联服务实现类
 * @author Wu.Liang
 * @since 2025-06-29
 */
@Slf4j
@Service
public class UserPropertyCompanyServiceImpl extends ServiceImpl<UserPropertyCompanyMapper, UserPropertyCompany> 
    implements IUserPropertyCompanyService {

    @Override
    @GlobalTransactional
    public Result<Void> assignUserToPropertyCompany(Long userId, Long propertyCompanyId, 
                                                   String position, String department, String employeeNo) throws Exception {
        log.info("为用户分配物业公司，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId);
        
        // 检查是否已存在关联
        if (isUserAssignedToPropertyCompany(userId, propertyCompanyId)) {
            return Result.fail("用户已关联该物业公司");
        }
        
        // 创建关联记录
        UserPropertyCompany userPropertyCompany = new UserPropertyCompany();
        userPropertyCompany.setUserId(userId);
        userPropertyCompany.setPropertyCompanyId(propertyCompanyId);
        userPropertyCompany.setPosition(position);
        userPropertyCompany.setDepartment(department);
        userPropertyCompany.setEmployeeNo(employeeNo);
        userPropertyCompany.setJoinDate(LocalDate.now());
        userPropertyCompany.setStatus(1); // 在职
        userPropertyCompany.setCreateBy(SecurityUtils.getCurrentUserId());
        userPropertyCompany.setCreateTime(LocalDateTime.now());
        userPropertyCompany.setUpdateBy(SecurityUtils.getCurrentUserId());
        userPropertyCompany.setUpdateTime(LocalDateTime.now());
        
        boolean success = this.save(userPropertyCompany);
        if (success) {
            log.info("用户分配物业公司成功");
            return Result.success();
        } else {
            return Result.fail("用户分配物业公司失败");
        }
    }

    @Override
    @GlobalTransactional
    public Result<Void> removeUserFromPropertyCompany(Long userId, Long propertyCompanyId) throws Exception {
        log.info("移除用户与物业公司的关联，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId);
        
        LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPropertyCompany::getUserId, userId);
        queryWrapper.eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId);
        
        boolean success = this.remove(queryWrapper);
        if (success) {
            log.info("移除用户物业公司关联成功");
            return Result.success();
        } else {
            return Result.fail("移除用户物业公司关联失败");
        }
    }

    @Override
    @GlobalTransactional
    public Result<Void> updateUserPropertyCompanyInfo(Long userId, Long propertyCompanyId,
                                                   String position, String department, String employeeNo) {
        log.info("更新用户在物业公司的信息，用户ID：{}，物业公司ID：{}", userId, propertyCompanyId);
        
        LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPropertyCompany::getUserId, userId);
        queryWrapper.eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId);
        
        UserPropertyCompany userPropertyCompany = this.getOne(queryWrapper);
        if (userPropertyCompany == null) {
            return Result.fail("用户物业公司关联不存在");
        }
        
        // 更新信息
        userPropertyCompany.setPosition(position);
        userPropertyCompany.setDepartment(department);
        userPropertyCompany.setEmployeeNo(employeeNo);
        userPropertyCompany.setUpdateBy(SecurityUtils.getCurrentUserId());
        userPropertyCompany.setUpdateTime(LocalDateTime.now());
        
        boolean success = this.updateById(userPropertyCompany);
        if (success) {
            log.info("更新用户物业公司信息成功");
            return Result.success();
        } else {
            return Result.fail("更新用户物业公司信息失败");
        }
    }

    @Override
    public List<UserPropertyCompany> getUserPropertyCompanies(Long userId) throws Exception {
        LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPropertyCompany::getUserId, userId);
        queryWrapper.eq(UserPropertyCompany::getStatus, 1); // 在职状态
        //queryWrapper.orderByDesc(UserPropertyCompany::getCreateTime);
        
        return this.list(queryWrapper);
    }

    @Override
    public List<UserPropertyCompany> getPropertyCompanyUsers(Long propertyCompanyId) throws Exception {
        log.info("获取物业公司的用户列表，物业公司ID：{}", propertyCompanyId);
        
        LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId);
        queryWrapper.eq(UserPropertyCompany::getStatus, 1); // 在职状态
//        queryWrapper.orderByDesc(UserPropertyCompany::getCreateTime);
        
        return this.list(queryWrapper);
    }

    @Override
    public boolean isUserAssignedToPropertyCompany(Long userId, Long propertyCompanyId) throws Exception {
        LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPropertyCompany::getUserId, userId);
        queryWrapper.eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId);
        queryWrapper.eq(UserPropertyCompany::getStatus, 1); // 在职状态
        
        return this.count(queryWrapper) > 0;
    }

	@Override
	public List<Long> getUserIdsByPropertyCompanyId(@NotNull Long propertyCompanyId) throws Exception {
		LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPropertyCompany::getPropertyCompanyId, propertyCompanyId);
        return this.list(queryWrapper).stream().map(UserPropertyCompany::getUserId).distinct().collect(Collectors.toList());
	}

	@Override
	public List<Long> getUserIdsByPropertyCompanyIds(@NotNull List<Long> propertyCompanyIds) throws Exception {
		if (propertyCompanyIds == null || propertyCompanyIds.size()==0) {
			return Collections.emptyList();
		}
		LambdaQueryWrapper<UserPropertyCompany> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserPropertyCompany::getPropertyCompanyId, propertyCompanyIds);
        return this.list(queryWrapper).stream().map(UserPropertyCompany::getUserId).distinct().collect(Collectors.toList());
	}
}
